package com.ms.pda.base

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.ms.architecture.base.BaseApplication
import com.ms.architecture.base.DataBindingFragment

abstract class BaseFragment : DataBindingFragment() {

    private var mFragmentProvider: ViewModelProvider? = null
    private var mActivityProvider: ViewModelProvider? = null
    private var mApplicationProvider: ViewModelProvider? = null

    protected open fun <T : ViewModel> getFragmentScopeViewModel(modelClass: Class<T>): T {
        if (mFragmentProvider == null) {
            mFragmentProvider = ViewModelProvider(this)
        }
        return mFragmentProvider!![modelClass]
    }

    protected open fun <T : ViewModel> getActivityScopeViewModel(
        activity: AppCompatActivity,
        modelClass: Class<T>
    ): T {
        if (mActivityProvider == null) {
            mActivityProvider = ViewModelProvider(activity)
        }
        return mActivityProvider!![modelClass]
    }

    protected open fun <T : ViewModel> getApplicationScopeViewModel(modelClass: Class<T>): T {
        if (mApplicationProvider == null) {
            mApplicationProvider =
                ViewModelProvider((mActivity!!.applicationContext as BaseApplication))
        }
        return mApplicationProvider!![modelClass]
    }
}